const AV = require('leanengine')
const fs = require('fs')
const path = require('path')
const axios = require('axios')

const config = {
  token: '********', //对应测试号接口配置信息里填的 token, 随便填什么
  appid: 'wxea438b3ef2920c0e', //对应测试号信息里的 appID
  secret: 'f3f2e0ee1b4af847412b880a94964ff3', //对应测试号信息里的 appsecret
  grant_type: 'client_credential', //默认
  tousers:['hhthhtabc','hxxxhnnn']// 测试公众号处显示的要接收人的微信号
};
// 
/**
 * Loads all cloud functions under the `functions` directory.
 */
fs.readdirSync(path.join(__dirname, 'functions')).forEach(file => {
  require(path.join(__dirname, 'functions', file))
})

/**
 * A simple cloud function.
 */
AV.Cloud.define('******', function () { // **** 代表云函数名
  (function getAccessToken() {
    const appid = config.appid;
    const secret = config.secret;
    const grant_type = config.grant_type;

    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=${grant_type}&appid=${appid}&secret=${secret}`;

    axios.get(url).then(res => {
        if (res.status === 200) {
            getWeather(res.data.access_token)
        } else {
            throw '获取access_token失败,请检查appid和secret'
        }
    }).catch(err => {
        console.log(err)
    })
})()

// 获取当天天气情况
function getWeather(access_token) {
    // 刚刚和风天气的api 
    axios.get('https://devapi.qweather.com/v7/weather/3d?location=101131101&key=*************').then((res, res2) => {
        sendTemplateMsg(access_token, res.data.daily[0]); //获取access_token成功后调用发送模板消息的方法
    })
}

// 计算是周几
function getTodayofSeven() {
    var now = new Date();
    var day = now.getDay();
    var text = "";
    console.log('模板消息推送成功 day = ' + day);
    switch (day) {
      case 1:
        text = "今天比昨天更爱你了哟，新的一周开始了，加油，宝贝儿，想你";
        break;
      case 2:
        text = "今天比昨天更爱你了哟，搬砖快乐哦，宝贝儿，想你";
        break;
      case 3:
        text = "今天比昨天更爱你了哟，一周已过半，继续加油，宝贝儿，想你";
        break;
      case 4:
        text = "今天比昨天更爱你了哟，周四周四，V我50，宝贝儿，想你";
        break;
      case 5:
        text = "今天比昨天更爱你了哟，马上周末，可以见到宝贝儿了，想你";
        break;
      case 6:
        text = "今天比昨天更爱你了哟，周末开始啦，好好休息，放松一下疲惫的身体，宝贝儿，想你";
        break;
      case 0:
        text = "今天比昨天更爱你了哟，抓紧最后一天休息时间，多陪陪他，宝贝儿，想你";
        break;
    }
    return text;
}

/**
 * 比如：5月21号
 * @param {*} month 阳历月份，5
 * @param {*} day   阳历几号，21
 * @returns 计算还有多少天过生日
 */
function getDaysToBirthday(month, day){
  var now = new Date();
  var thisYear = now.getFullYear();
  // 今年的生日
  var birthday = new Date(thisYear, month - 1, day);
  if(birthday < now) {
    birthday.setFullYear(now.getFullYear()+1);
  }
  var timeDec = birthday - now;
  var days = timeDec / (24 * 60 * 60 * 1000);
  return Math.ceil(days);
}


function sendTemplateMsg(access_token, res) {
    var today = new Date().toLocaleDateString();
    var endTime4Know = parseInt(new Date().getTime() / 1000) - new Date('2022-8-10 00:00:00').getTime() / 1000;
    var endTime4Love = parseInt(new Date().getTime() / 1000) - new Date('2022-11-6 00:00:00').getTime() / 1000;
    var knowDays = parseInt(endTime4Know / 60 / 60 / 24);
    var loveDays = parseInt(endTime4Love / 60 / 60 / 24); 
    var birthDays1 = getDaysToBirthday(2, 27);
    var birthDays2 = getDaysToBirthday(6, 15);
    var firstDayOfYear = getDaysToBirthday(1, 1);
    var newYear = getDaysToBirthday(1, 21);
    var startText = getTodayofSeven();
    const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`; //发送模板消息的接口
    const requestData = { //发送模板消息的数据
        template_id: '**********************',//消息的模板id
        url: 'http://weixin.qq.com/download',
        data: {
            name: {
                value: '小猪',
                color: "#173177"
            },
            link: {
                value: 'https://blog.csdn.net/u011489043?type=blog',
                color: '#1d1d1d'
            },
            city: {
                value: '北京-朝阳区',
                color: '#1d1d1d'
            },
            startText: {
                value: startText,
                color: '#FF0000'
            },
            textDay: {
                value: res.textDay,
                color: '#228B22'
            },
            tempMin: { //最低温
                value: res.tempMin + '℃',
                color: '#1d1dff'
            },
            tempMax: { //最高温
                value: res.tempMax + '℃',
                color: '#ff1d1d'
            },
            windScaleDay: { // 白天风力等级
              value: res.windScaleDay + '级',
              color: '#8B4513'
            },
            windScaleNight: { // 夜间风力等级
              value: res.windScaleNight + '级',
              color: '#8B4513'
            },
            date: { // 
              value: today,
              color: '#000000'
            },
            know_day: { //
              value: knowDays,
              color: '#FF69B4'
            },
            love_day: { //
              value: loveDays,
              color: '#FF69B4'
            },
            birthday1: { //
              value: birthDays1,
              color: '#FF00FF'
            },
            birthday2: { //
              value: birthDays2,
              color: '#000000'
            },
            firstDayOfYear: {
              value: firstDayOfYear,
              color: '#8B0000'
            },
            newYear: {
              value: newYear,
              color: '#8B0000'
            },
        
        }
    };

    config.tousers.forEach(item => {
        requestData.touser = item
        axios.post(url, requestData).then(res => {
            if (res.status === 200) {
                console.log('模板消息推送成功');
            } else {
                throw '模板消息推送失败'
            }
        }).catch(err => {
            console.log(err)
        })
    })
  }
})


